import time,redis
from datetime import datetime
from decimal import Decimal
from flask import Blueprint, jsonify, request,session
from ..extensions import qhjy_db,jys_db,pool
from ..utils.binance import getETHBinance,getETHBinanceForOne
from ..utils.computeGains import compute_gains
from ..utils.token import check_activate_token
from ..utils.decimal_to_float import decimal_to_float
eth_qhjy = Blueprint('eth_qhjy', __name__)


# 最近十期七家交易所BTC数据
@eth_qhjy.route('/result/',methods=['GET', 'POST'])
def result():
    sql='select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current in (0,2) and qh_nper.id in (select A.id from (select id from qh_nper where qh_nper.coin_id=24 and is_current in (0,2) ORDER by id DESC limit 10) as A)'

    #sql='select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current in (0,2) and qh_nper.id in (select A.id from (select id from qh_nper where qh_nper.coin_id=24 and is_current in (0,2) ORDER by id DESC limit 10) as A) '
    res = qhjy_db.selectall(sql)
    l=list(set([r["nper"] for r in res]))
    l=list(sorted(l,reverse=True))
    nperdict={i:[] for i in l}
    for r in res:
        if r:
            r['rose'], r["consequence"] = compute_gains(r['open_time_price'], r['end_time_price'])
            decimal_to_float(r)
            nperdict[r["nper"]].append(r)
    mlist=[]
    for i,j in nperdict.items():
        mlist.append({i:j})
    return jsonify({'code': 1, 'datas': mlist, 'msg': '返回最新十期数据'})


#买涨,买平,买跌
@eth_qhjy.route('/operation/<int:uid>/',methods=['GET', 'POST'])
def operation(uid):
    #检查是否开盘时间
    m = (datetime.now().minute) % 10
    s = datetime.now().second
    if m == 4 and s in range(50, 60):
        return  jsonify({'code': 0, 'data': '', 'msg': '现在不是开盘时间 请等待开盘'})
    #获得配置参数
    config=qhjy_db.selectone('select is_open,btc_error,eth_error from qh_config')
    if not config['is_open']:
        return jsonify({'code': 0, 'data': '', 'msg': '现在不是开盘时间 请等待开盘'})
    if config['btc_error']==1:
        return  jsonify({'code': 0, 'data': '', 'msg': 'BTC正在维护中'})
    # 获取投注价格
    try:
        price = Decimal(request.form.get('price'))
    except:
        return jsonify({'code': 0, 'data': '', 'msg': '非法数据,请重新输入'})
    token=request.cookies.get('token')
    if token and check_activate_token(token) == session['id']:
        user_id = session["id"]
        # 从连接池中获取redis
        redis_store = redis.Redis(connection_pool=pool)
        #获取资金情况
        finance=jys_db.selectone('select * from bf_user_coin where userid=%d' % int(user_id))
        #获取该期数据情况
        nper=qhjy_db.selectone('select * from qh_nper where coin_id=24 and is_current = 1')
        nper_id=nper["id"]
        #检查余额是否充足
        if price > finance["btc"]:
            return jsonify({'code': 0, 'data': '', 'msg': 'BTC余额不足'})
        #redis记录投注总金额
        if uid == 1:
            redis_store.set('user_betting_record_to_w_14342_3', price)
        if uid == 2:
            flat_price = float(redis_store.get('qh_flat_price_btc')) + float(price)
            redis_store.set('qh_flat_price_btc', flat_price)
        if uid == 3:
            down_price = float(redis_store.get('qh_down_price_btc')) + float(price)
            redis_store.set('qh_down_price_btc', down_price)
        # 检查该用户该期是否在该类型有下注
        bet = qhjy_db.selectone("select * from qhjy.qh_betting where user_id=%d and tw_qh_coin=24 and nper_id=%d and `type`=%d"%(user_id,nper_id,uid))
        # 没下注
        if not bet:
            sql = 'insert into qhjy.qh_betting(user_id,tw_qh_coin,nper_id,`type`,price,add_time,is_true) values({},24,{},{},{},{},1);'.format(user_id, nper_id, uid, price, int(time.time()))
            qhjy_db.execute(sql)
            qhjy_db.execute('insert into qh_betting_false VALUE (0,{},{},{},{},{},{},{})'.format(user_id,session["mobile"],price,uid,24,nper_id,0.1,int(time.time())))
        #下注
        else:
            price = bet["price"] + price
            sql = 'update qhjy.qh_betting set price=%f,add_time=%d where id=%d'%(price,int(time.time()),bet["id"])
            qhjy_db.execute(sql)
            sql='insert into qh_betting_false VALUE (0,{},{},{},{},{},{},{})'.format(user_id,session["mobile"],float(price),uid,24,nper_id,0.1,int(time.time()))
        bet = qhjy_db.selectone("select * from qhjy.qh_betting where user_id=%d and tw_qh_coin=24 and nper_id=%d and `type`=%d" % (user_id, nper_id, uid))
        decimal_to_float(bet)
        #redis个人投注记录
        # redis_store.set('user_betting_record_to_w_%s_3'%str(session["id"]), jsonify(bet))
        # if redis_store.llen('qh_ecord_betting')>=100:
        #     redis_store.lpop("qh_ecord_betting")
        mobile = str(session["mobile"])[:3] + '****' + str(session["mobile"])[:7]
        redis_store.lpush("qh_ecord_betting", json.dumps([mobile, float(price), uid, 24, int(time.time()), 0.1]))
        redis_store.lpush("qh_ecord_betting2", json.dumps([mobile, float(price), uid, 24, int(time.time()), 0.1]))
        #冻结资金
        new_btc=finance['btc']-price
        new_btcd=finance['btcd']+price
        jys_db.execute('update bf_user_coin set btc={},btcd={} where userid={}'.format(new_btc,new_btcd,user_id))
        #搜集返回的数据(期号,买了涨跌平,是BTC还是ETH,多少,多长时间会交割)
        mdict={}
        mdict["nper"]=nper["nper"]
        mdict["t"] = nper["open_time"] + 600
        mdict["price"] = float(price)
        mdict["type"] = "BTC"
        mdict["status"]=uid
        return jsonify({'code': 1, 'datas': mdict, 'msg': '投注成功'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})
#涨,平,跌赔率接口
@eth_qhjy.route('/vote/',methods=['GET', 'POST'])
def vote():
    res=qhjy_db.selectone('select up_rate,down_rate,flat_rate from qh_nper where coin_id=24 and is_current = 1 ')
    res['up_rate']='{0:.3%}'.format(float(res['up_rate']))
    res['down_rate'] = '{0:.3%}'.format(float(res['down_rate']))
    res["flat_rate"]='{0:.3%}'.format(float(res["flat_rate"]))
    return jsonify({'code': 1, 'data': res, 'msg': ''})

#买涨,买平,买跌总数量
@eth_qhjy.route('/aaa/',methods=['GET', 'POST'])
def aaa():
    token=request.cookies.get('token',None)
    if token and check_activate_token(token) == session['id']:
        redis_store = redis.Redis(connection_pool=pool)
        mdict={}
        mdict["up"]=round(float(redis_store.get('qh_up_price_btc')),4)
        mdict["flat"] = round(float(redis_store.get('qh_flat_price_btc')),4)
        mdict["down"] = round(float(redis_store.get('qh_down_price_btc')),4)
        mdict["all"]=round(mdict["up"]+mdict["flat"]+mdict["down"],4)
        btc_price = float(jys_db.selectone('select price from tw_btc where id=1')["price"])
        mdict["allCNY"]=int(btc_price*float(mdict["all"]))
        return jsonify({'code': 1, 'data': mdict, 'msg': ''})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户没登录'})



#当前结果(期号,点差,d)
@eth_qhjy.route('/now_result/',methods=['GET', 'POST'])
def now_result():
    minute=datetime.now().minute
    if minute%5==0:
        sql = 'select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate,qh_nper.open_time from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current=2 and  qh_result.exchange_name in (1,2,3,4,7) GROUP by qh_result.exchange_name ORDER by qh_result.coin_id'
        res = qhjy_db.selectall(sql)
        #end = int(time.time())
        # if end - res["open"] - 600 > 60:
        #     sql = 'update qhjy.qh_config set btc_error=1 '
        #     qhjy_db._Connection__execute(sql)
        #     return jsonify({'code': -1, 'datas': '', 'msg': '数据超时'})
        if res:
            if  len(res)==5:
                for r in res:
                    r['rose'],r["consequence"] = compute_gains(r['open_time_price'],r['end_time_price'])
                    decimal_to_float(r)
                return jsonify({'code': 1, 'datas': res, 'msg': '返回当前数据'})
            else:
                return jsonify({'code': 0, 'datas': '', 'msg': '数据不够'})
        else:
            return jsonify({'code': 0, 'datas': '', 'msg': '没有数据'})
    else:
        return jsonify({'code': 0, 'data': "", 'msg': '还没到交割时间呢'})



#最近一期七家交易所BTC数据(期号,张平,点差)
@eth_qhjy.route('/latest_result/',methods=['GET', 'POST'])
def latest_result():
    #res = qhjy_db.selectall('select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current = 2 and qh_result.exchange_name in (1,2,3,4,7) GROUP by qh_result.exchange_name ORDER by qh_result.coin_id')
    res = qhjy_db.selectall('select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current = 2')
    for r in res:
        r['rose'], r["consequence"] = compute_gains(r['open_time_price'], r['end_time_price'])
        decimal_to_float(r)
    return  jsonify({'code': 1, 'datas': res, 'msg': '返回最新数据'})

import requests,json


#币安交易所开始
@eth_qhjy.route('/global_market/',methods=['GET', 'POST'])
def global_market():
    return jsonify({'code': 0, 'datas': getETHBinance(), 'msg': '查询不到最新一期的期号'})

#币安交易所一分钟
@eth_qhjy.route('/global_market_one/',methods=['GET', 'POST'])
def global_market_one():
    return jsonify({'code': 0, 'datas': getETHBinanceForOne(), 'msg': '查询不到最新一期的期号'})



#最近谁投了(查询redis)

'''
@btc_qhjy.route('/btc_last/',methods=['GET', 'POST'])
def btc_last():
'''
 # mdict2["%d:%d" % (user_id, 3)] = price

#倒计时
'''
通知开盘
btc结果通知后续操作(结果要存到nper里面)
'''
@eth_qhjy.route('/last/',methods=['GET', 'POST'])
def last():
    redis_store = redis.Redis(connection_pool=pool)
    t = redis_store.get("qh_current_time_info_24")
    # print(redis_store.keys("user_betting_record_to_w_*_3"))
    if t:
        data = json.loads(t.decode('utf-8'))
    else:
        data = qhjy_db.selectone('select a.end_time,a.open_time,b.end_time as next_end_time,b.stop_time as next_stop_time,a.stop_time from (select nper,end_time,open_time,stop_time from qh_nper where is_current=1 and coin_id=24) a,(select nper,end_time,open_time,stop_time from qh_nper where is_current=3 and coin_id=24) b')
    data["current_time"] = int(time.time())
    return jsonify({'code': 1, 'data': data, 'msg': ''})